from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.template import Context, loader
from django.shortcuts import render_to_response

from google.appengine.api import users
from django.utils  import simplejson as json
import logging

from django.core import serializers
import time
from home.models import Note

def post_nost(request): 
  user = users.get_current_user()
  if user:   
  	nickname = user.nickname()
  	gmail = user.email()
  	noteContent = request.REQUEST.get('note', '');
  	
  	note = Note(notePoster=nickname,gmail=gmail,noteContent=noteContent);
  	note.put();
  	logging.info("post stored");
  else:
    logging.warn("Invalid update request from "+request.get_host())

    
def request_update(request):
  results = Note.all().order('-postDate')
  notesCount = results.count()   
  notesContent = serializers.serialize("json",results)  
  rows = json.loads(notesContent)
  s = '['
  for i in range(0,notesCount):	  
	  row = rows[i]['fields']
	  row = json.dumps(row)
	  s = s  + row + ',' 
  s = s+']'
  #logging.info( "request_update:"+s ); 
  return HttpResponse(s);
  
def request_delete(request):  
  user = users.get_current_user()
  if user:   
  	nickname = user.nickname()
  	gmail = user.email()
  	noteContent = request.REQUEST.get('noteContent', '');
  	
  	query = Note.gql("WHERE gmail = :1 AND noteContent = :2",
                  gmail,noteContent)
  	query.fetch(1)[0].delete()
   	logging.info("note deleted");
  else:
    logging.warn("Invalid request_delete request from "+request.get_host())

def profile(request):
   
  d = dict();
  user = users.get_current_user()  
  gmail = ""
  nickname = ""
  if user:
      gmail= user.email()
      nickname = user.nickname()
      sign_url = users.create_logout_url("/")
  else:
      sign_url = users.create_login_url("/")  
  
  d['gmail']=gmail
  d['sign_url']=sign_url
  data =  json.dumps(d)
  
  return HttpResponse('['+data+']');
  


def index(request):
  return HttpResponseRedirect('www/h/Home.html')



	
